// javamaps
// Copyright (c) 2010 Vasiu Cristina
package Utils.PathFinder;


import Core.*;
import Core.Link;
import Core.Street;
import java.util.*;
import java.util.ArrayList;
import Data.FileMapProvider;
import Core.IMapProvider;
import Projection.MercatorProjection;
import java.lang.Math;


public class DikstraAlgorithm {


    Map <ObjectId, Vertex> hashVertex_;
    double distance_;  
    //IMapProvider provider_;

    public DikstraAlgorithm(){
       
        hashVertex_  = new HashMap<ObjectId, Vertex>();       
        distance_ = 0;
      
    }
   /* public Route Route() { return route_; }
    public void SetRoute(Route route) {route_ = route; }*/

    public void Dikstra(IMapProvider provider, Vertex source, Vertex destination){

        source.SetMinDistance(0.0);

        PriorityQueue vertexQueue = new PriorityQueue<Vertex>();
        vertexQueue.add(source);

        while(vertexQueue.isEmpty() == false){


           Vertex vertex = (Vertex) vertexQueue.poll();
           hashVertex_.put(vertex.Node().Id(), vertex);

           Iterator<Link> linkIt = vertex.Node().Iterator();

           while(linkIt.hasNext()) {

               Link link = linkIt.next();
               Vertex nearVertex;
               Node nearNode = (Core.Node)(provider.GetNode(link.NodeId()));

               if(hashVertex_.containsKey(nearNode.Id()) == false)

                   nearVertex = new Vertex(nearNode);

               else

                   nearVertex = hashVertex_.get(nearNode.Id());

               double weight =  link.Distance();
               distance_ = vertex.MinDistance() + weight;

               if (distance_ < nearVertex.MinDistance()){

                   hashVertex_.remove(nearVertex.Node().Id());
                   vertexQueue.remove(nearVertex);

                   nearVertex.SetMinDistance(distance_);
                   nearVertex.SetPrevious(vertex);

                   hashVertex_.put(nearVertex.Node().Id(), nearVertex);
                   vertexQueue.add(nearVertex);


                }

            }

        }
    }

}
